import React, { Component } from 'react';
import styles from './index.module.scss';
import { withRouter } from 'next/router';
import { connect } from 'react-redux';
import { conversationList, delConversation } from '@/api/ai';
import router from 'next/router';
import { motion } from 'framer-motion';
import ConfirmDialog from '@/components/basicComp/Confirm';
import classNames from 'classnames';
import { Search } from 'lucide-react';
import { openDevTools } from '@/utils/electron';

@withRouter
@connect(({ space }) => ({
  space,
}))
class Comp extends Component {
  bodyContRef = React.createRef();
  componentDidMount = () => {
    this.getList();
    // 恢复 bodyCont 滚动位置
    if (typeof window !== 'undefined' && this.bodyContRef.current) {
      const scrollY = window.localStorage.getItem('space_bodyCont_scrollY');
      if (scrollY) {
        this.bodyContRef.current.scrollTop = parseInt(scrollY, 10);
      }
    }
  };

  componentWillUnmount() {
    // 记录 bodyCont 滚动位置
    if (typeof window !== 'undefined' && this.bodyContRef.current) {
      window.localStorage.setItem(
        'space_bodyCont_scrollY',
        this.bodyContRef.current.scrollTop,
      );
    }
  }

  changeState = (obj) => {
    this.props.dispatch({
      type: 'space/setState',
      payload: obj,
    });
  };

  getList = async () => {
    var rs = await conversationList();
    if (rs.data?.code == 200) {
      var data = rs.data.data.map((item) => {
        return {
          ...item,
          title: item.theme,
          date: item.created,
        };
      });
      data.reverse()
      this.changeState({ chatsList: data });
    }
  };

  toggleSelectAll = () => {
    const { selectAll, chatsList } = this.props.space;
    const newSelectAll = !selectAll;

    var selectMaps = {};
    if (newSelectAll) {
      chatsList.forEach((item) => {
        selectMaps[item.id] = item.id;
      });
    }

    this.changeState({
      selectAll: newSelectAll,
      selectMaps: selectMaps,
    });
  };

  toggleSelectChat = (e, id) => {
    var checked = e.target.checked;
    const { selectMaps, chatsList } = this.props.space;
    var sMap = { ...selectMaps };
    if (checked) {
      sMap[id] = id;
    } else {
      delete sMap[id];
    }

    var obj = {
      selectMaps: sMap,
      selectAll: Object.keys(sMap).length == chatsList.length ? true : false,
    };
    this.changeState(obj);
  };

  deleteSelected = async () => {
    const { selectMaps } = this.props.space;
    this.changeState({ confirmOpen: false });

    var delList = Object.keys(selectMaps);
    var rs = await delConversation({
      id_list: delList,
    });

    if (rs.data?.code == 200) {
      this.delChatId(delList)
      this.changeState({ selectMaps: {} });
      this.getList();
    }
  };

  delChatId = (delList) => {
    var selectedChat = window.localStorage.getItem('selectedChat');
    if (selectedChat) {
      if (delList.indexOf(selectedChat) != -1) {
        window.localStorage.removeItem('selectedChat')
      }
    }
  }

  handleSelectToggle = () => {
    const { selectMode } = this.props.space;
    this.changeState({ selectMode: !selectMode });
  };

  render() {
    const {
      chatsList,
      isAll,
      selectMaps,
      selectAll,
      search,
      selectMode,
      confirmOpen,
    } = this.props.space;
    var list = [...chatsList];
    if (search) {
      const s = search.trim().toLowerCase();
      list = list.filter((item) =>
        (item.title || '').toLowerCase().includes(s),
      );
    }
    if (!isAll) list.length = 10;

    return (
      <motion.div
        initial={{ opacity: 0 }} // 初始状态：不透明度为 0
        animate={{ opacity: 1 }} // 动画状态：不透明度为 1
        transition={{ duration: 0.5 }} // 动画持续时间为 1 秒
        style={{ height: '100%' }}
      >
        <div className={styles.container}>
          <div className={styles.header}>
            <h2>Your Chat History</h2>
            <button
              className={styles.newChatButton}
              onClick={() => {
                window.localStorage.removeItem('selectedChat');
                router.push('/chat');
              }}
            >
              <i style={{ marginRight: '5px' }} className='iconfont icon-tianjia'></i>
              New chat
            </button>
          </div>

          <div className={styles.searchContainer}>
            {/* <div className={styles.searchBox}> */}
              <Search className={styles.searchIcon} />
              <input
                type="text"
                placeholder="Search modes..."
                className={styles.searchInput}
                value={search}
                onChange={(v) => {
                  this.changeState({ search: v.target.value });
                }}
              />
            {/* </div> */}
          </div>

          <div className={styles.chatInfoHeader}>
            <p>You have {chatsList.length} previous chats with Efflux</p>

            <div className={styles.actionButtons}>
              {/* 只有在选择模式下显示其他按钮 */}
              {/* {selectMode && ( */}
              <div className={styles.otherActions} style={{ opacity: selectMode ? 1 : 0,visibility: selectMode ? 'visible' : 'hidden'}} >
                <label className={styles.selectAllLabel}>
                  <input
                    type="checkbox"
                    checked={selectAll}
                    onChange={this.toggleSelectAll}
                  />
                  Select All
                </label>
                <button
                  className={styles.deleteButton}
                  onClick={() => {
                    if(!selectMode) return
                    this.changeState({ confirmOpen: true });
                  }}
                  disabled={Object.keys(selectMaps).length == 0}
                >
                  <i style={{marginRight: '5px'}} className='iconfont icon-Delete'></i>
                  Delete Selected
                </button>
              </div>
              {/* )} */}

              <button
                className={styles.selectButton}
                onClick={this.handleSelectToggle}
              >
                {'Select'}
              </button>
            </div>
          </div>

          <div className={styles.body}>
            <div className={styles.bodyCont} ref={this.bodyContRef}>
              <div className={styles.chatList}>
                {list.map((chat) => (
                  <div key={chat.id} className={styles.chatItem} onClick={() => {
                    if (!selectMode) {
                      var name = 'selectedChat'
                      var path = '/chat'
                      
                      if(chat.type == 'plan'){
                          name = 'selectedPlanChat'
                          path = '/ppt' 
                      }
                      window.localStorage.setItem(name, chat.id);
                      router.push(path);
                    }
                  }}>
                    <div
                      className={classNames(styles.checkboxContainer, {
                        [styles.checkboxContainerVisible]: selectMode,
                      })}
                    >
                      <input
                        type="checkbox"
                        checked={selectMaps[chat.id] ? true : false}
                        onChange={(e) => this.toggleSelectChat(e, chat.id)}
                      />
                    </div>
                    <div style={{ paddingLeft: selectMode ? 0 : '24px',transition:'padding-left 0.3s ease' }} className={styles.chatContent}>
                      <h3
                        onClick={() => {
                          if (selectMode) {
                            window.localStorage.setItem('selectedChat', chat.id);
                            router.push('/chat');
                          }
                        }}
                      >
                        {chat.title}
                      </h3>
                      <p>
                        {(()=>{
                          var content = chat?.last_dialog_segment?.content
                          console.log(chat)
                           if(Array.isArray(content) && content[0]){
                            return content[0].content
                           }else{
                            return content
                           }
                        })()}
                        </p>
                      <div className={styles.chatDate}>
                        {/* <span className={styles.dateIcon}></span> */}
                        <i style={{ marginRight: '5px' }} className='iconfont icon-shijian' ></i>
                        <span>{chat.date}</span>
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          </div>

          {chatsList.length > 10 && !search && (
            <div
              className={styles.viewAllContainer}
              style={{ 
                height: !isAll ? '33px' : 0,
                marginTop: !isAll ? '20px' : 0
              }}
            >
              <button
                className={styles.viewAllButton}
                onClick={() => {
                  this.changeState({ isAll: true });
                }}
              >
                View All
              </button>
            </div>
          )}

          <ConfirmDialog
            isOpen={confirmOpen}
            title={`Confirmation`}
            message="Are you sure to delete the model? You can continue to configure the model after deletion."
            onCancel={() => {
              this.changeState({ confirmOpen: false });
            }}
            onConfirm={() => {
              this.deleteSelected();
            }}
            cancelText="Cancel"
            confirmText="Delete"
          />

          <div className={styles.footerBox}
            onClick={()=>{
              this.props.dispatch({
                type: 'global/setState',
                payload: { showSetApiUrl: true },
              });
              openDevTools()
            }}
          ></div>
        </div>
      </motion.div>
    );
  }
}

export default Comp;
